package de.rac.vaadin.framework.ui;
/*******************************************************************************
 * Utilities to encode and decode the password<br>
 * @author Volodymyr Dobryvechir (dobrivecher@yahoo.com)
 * @version 0.2 31.05.2012  <br>
 ******************************************************************************/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncodingUtils {
	public static String getEncodedPassword(String password,MessageDigest md)
	{
		if (password==null || password.length()==0) return "";
        String clearPassword = password.trim();
        if (md==null) return clearPassword;
        md.update(clearPassword.getBytes());
        byte[] digestedPassword = md.digest();
        StringBuilder res = new StringBuilder();
        for(int i=0;i<digestedPassword.length;i++)
        {
        	res.append(Integer.toHexString(digestedPassword[i] & 0xff)); 
        }
        return res.toString();		
	}
	public static String getEncodedPassword(String password,String algorithm) 
    {
		if (password==null || password.length()==0) return "";
        String clearPassword = password.trim();
        MessageDigest md;
        try
        {
        	md=getPasswordMessageDigest(algorithm);
        }
        catch(Exception NoSuchAlgorithmException)
        {
        	throw new RuntimeException("Unsupported encoding algorithm: "+algorithm);
        }
		return getEncodedPassword(clearPassword,md);
    }	
	public static String getPasswordAlgorithm(ResourcePool resource) throws NoSuchAlgorithmException
	{
		String algorithm = resource.getConfigParameterDirectly("password_alrorithm");
        if (algorithm==null) return null;
		algorithm=algorithm.trim().toUpperCase();
		if (algorithm.equals("NONE")) return null;
		MessageDigest.getInstance(algorithm);
		return algorithm;
	}
	public static MessageDigest getPasswordMessageDigest(String algorithm) throws NoSuchAlgorithmException
	{
		if (algorithm==null) return null;
		algorithm=algorithm.trim().toUpperCase();
		if (algorithm.equals("NONE")) return null;
		MessageDigest md = MessageDigest.getInstance(algorithm); //SHA-1, MD5
        return md;		
	}
	public static MessageDigest getPasswordMessageDigest(ResourcePool resource) throws NoSuchAlgorithmException
	{
		String algorithm = getPasswordAlgorithm(resource);
		return getPasswordMessageDigest(algorithm);
	}
	public static String getEncodedPassword(String password,ResourcePool resource) throws NoSuchAlgorithmException
    {
		MessageDigest md=getPasswordMessageDigest(resource);
		return getEncodedPassword(password,md);
    }
	public static String getPureUserName(String userName,ResourcePool resource) throws Exception 
	{
		if (userName==null || userName.trim().length()==0) 
			throw new Exception(resource.getTranslation("UserNameIsNotSpecified"));
		return userName.trim();
	}
}
